#include <iostream>
#include <unistd.h>
#include <vector>
#include "CPHMediaEngine.h"

using namespace std;

static FILE *g_pcmFp = NULL;
static int g_count = 0;

void AudioCallbackFunc(uint8_t* data, uint32_t size, AudioCallbackExt& audioCallBackExt)
{
	if (g_pcmFp != nullptr) {
		fwrite(data, size, 1, g_pcmFp);
	}
	
	g_count++;
	if (g_count % 30 == 0) {
		std::cout << "frame size is : " << size << std::endl;
	}
}

int main(int argc, char* argv[])
{
	g_pcmFp = fopen("/data/8000hz.pcm", "wb");
	if (g_pcmFp == NULL) {
		std::cout << "open /data/output.pcm failed" << std::endl;
		return -1;
	}
	
	CPHMediaEngine mediaEngine;
	
	// 正常8000采样率单声道出流json串
	const char *jsonstr1 = "{\"samplerate\":8000, \"channels\":1, \"audioType\":1, \"interval\":10, \"bitrate\":16000}";
	
	int inputChar;
	int inputChar2;
	bool flag = true;
	while (flag) {
		std::cout << "input 1 to set..." << std::endl;
		std::cout << "input 0 to exit..." << std::endl;
		std::cin >> inputChar;
		std::cout << std::endl;
		switch (inputChar) {
			case 1: {
				// CPHMediaEngine 5.0 API
				std::cout << "input 1 to open with correct json" << std::endl;
				std::cout << "input 2 to close mediaEngine" << std::endl;
				
				std::cin >> inputChar2;
				std::cout << std::endl;
				switch (inputChar2) {
					case 1: {
						if (mediaEngine.OpenAudio(jsonstr1, AudioCallbackFunc) != 0) {
							std::cout << "open with correct json failed." << std::endl;
						}
						break;
					}
					case 2: {
						if (mediaEngine.CloseAudio() != 0) {
							std::cout << "close audio failed!" << std::endl;
						}
						break;
					}
					default: {
						std::cout << "wrong!!! pls re-input..." << std::endl;
					}
				}
				break;
			}
			case 0: {
				std::cout << "exit program" << std::endl;
				if (mediaEngine.CloseAudio() != 0) {
					std::cout << "destroy audio failed!" << std::endl;
				}
				if (g_pcmFp != nullptr) {
					fclose(g_pcmFp);
					g_pcmFp = nullptr;
				}
				flag = false;
				break;
			}
			default: {
				std::cout << "wrong!!! pls re-input..." << std::endl;
			}
		}
	}
	
	return 0;
}